package com.songhq.data.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.songhq.data.bean.Response;
import com.songhq.data.log.util.LogUtil;
import com.songhq.data.redis.RedisUtil;


@Component
public class MyIntercepter implements HandlerInterceptor{
	
	
	@Autowired
	private RedisUtil redisUtil;

	//注意一下，springmvc5.x版本后  接口里的方法增加了default关键字
	//default关键字是 接口中的方法实现的子类可以不去实现
	@Override
	public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("application/json;charset=UTF-8");
       String userId = request.getHeader("userId");
      
	   if (StringUtil.isEmpty(userId)) {
	       LogUtil.info("请登入");
	       Response error = Response.error(401, "请登入");
	       String str = JSON.toJSONString(error);
	       response.setStatus(401);
	       response.getWriter().write(str);
	       return false;
	   } else {
       String name = (String)redisUtil.get(userId);
       if (StringUtil.isEmpty(name)) {
    	   Response error = Response.error(401, "身份已过期");
	       String str = JSON.toJSONString(error);
	       response.setStatus(401);
	       response.getWriter().write(str);
           return false;
       } else {
    	   //刷新生存时间
    	   redisUtil.set(userId, name, 60*1);
       }
       }
		return true;
	}

	
}
